package com.lm56.web.sys.controller;

import com.lm56.common.MyRequestBody;
import com.lm56.common.MyResponseBody;
import com.lm56.common.ServiceException;
import com.lm56.common.exception.FieldValidateExcetiption;
import com.lm56.web.CommonService;
import com.lm56.web.network.domain.Location;
import com.lm56.web.network.domain.ShippingType;
import com.lm56.web.security.SecUserDetails;
import com.lm56.web.sys.domain.User;
import com.lm56.web.sys.domain.UserContact;
import com.lm56.web.sys.domain.UserDetail;
import com.lm56.web.sys.domain.UserForm;
import com.lm56.web.sys.service.UserService;
import com.sun.javafx.sg.prism.NGShape;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.*;

/**
 * Created by Kelvin Yeung on 2016/11/20.
 */
@Controller
@RequestMapping(value = "/workbench")
public class ProfileController {


    Logger logger = LoggerFactory.getLogger(ProfileController.class);

    @Autowired
    ShippingTypesCollectionEditor shippingTypesCollectionEditor;
    @Autowired
    UserService userService;

    @Autowired
    CommonService commonService;


    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(List.class, "companyShippingTypes", shippingTypesCollectionEditor);
    }

    @RequestMapping(value = "profile",method = RequestMethod.GET)
    public String myprofile(Model model){
        SecUserDetails secUser= (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetail user = userService.getUserDetailById(secUser.getUserId());
        UserForm userForm = getUserForm(user);

        List<ShippingType> shippingTypes = commonService.getShippingTypeList();

        model.addAttribute("userForm",userForm);
        model.addAttribute("shippingTypes",shippingTypes);
        return "workbench/company/profile";
    }


    @RequestMapping(value = "profile",method = RequestMethod.POST)
    public  String myprofile(UserForm userForm,Model model){

        UserDetail userDetail = getUserDetail(userForm);
        userService.updateUserDetail(userDetail);

        List<ShippingType> shippingTypes = commonService.getShippingTypeList();
        model.addAttribute("shippingTypes",shippingTypes);
        model.addAttribute("success","cuccess");
        return "workbench/company/profile";
    }


    @RequestMapping(value = "profile/changepwd",method = RequestMethod.GET)
    public String changePassword(){

        return "workbench/changepwd";
    }

    @RequestMapping(value = "profile/changepwd",method = RequestMethod.POST)
    public String changePassword(String oldPwd,String newPwd ,Model model){


        try {
            userService.changePassowrd(oldPwd,newPwd);
        }catch (FieldValidateExcetiption e){
            model.addAttribute(e.getField()+"Err",e.getMessage());
            model.addAttribute("failed","failed");
           return "workbench/changepwd";
        }

        model.addAttribute("success","success");
        return "workbench/changepwd";
    }




    private UserForm getUserForm(UserDetail user){
        UserForm userForm = new UserForm();
        userForm.setPhoneNo(user.getPhoneNo());
        userForm.setPassword(user.getPassword());
        userForm.setEmail(user.getEmail());
        int userType = user.getUserType();
        userForm.setUserType(user.getUserType()); //1.company;2.sender;3.receiver;4.driver;5.other


        //公司
        if (userType == User.USER_TYPE_COMPANY) {

            userForm.setCompanyLocation(user.getLocation());

            userForm.setCompanyName(user.getUserName());
            userForm.setCompanyAddr(user.getUserAddr());



            //QQ

            String qqs= "";
            for(UserContact userContact1:user.getContactList())
            {
                if(userContact1.getContactType()==UserContact.CONTACT_TYPE_MOBILE_PHONE){
                    userForm.setCompanyContactName(userContact1.getContactName());
                    userForm.setCompanyContactPhoneNo(userContact1.getContactAccount());
                }else if(userContact1.getContactType() ==UserContact.CONTACT_TYPE_QQ){
                    qqs+=","+userContact1.getContactAccount();
                }
            }
            if(qqs.length()>0){
               qqs = qqs.substring(1,qqs.length());
            }
            userForm.setCompanyQQ(qqs);

            userForm.setCompanyShippingTypes(user.getShippingTypes());




        } else if (userType == User.USER_TYPE_SENDER) {
            userForm.setSenderLocation(user.getLocation());

            userForm.setSenderPhoneNo(user.getUserName());
            //QQ
            String qqs= "";
            for(UserContact userContact1:user.getContactList())
            {
                if(userContact1.getContactType()==UserContact.CONTACT_TYPE_MOBILE_PHONE){
                    userForm.setSenderName(userContact1.getContactName());
                    userForm.setSenderPhoneNo(userContact1.getContactAccount());
                }else if(userContact1.getContactType() ==UserContact.CONTACT_TYPE_QQ){
                    qqs+=","+userContact1.getContactAccount();
                }
            }
            if(qqs.length()>0){
                qqs = qqs.substring(1,qqs.length());
            }
            userForm.setSenderQQ(qqs);

            StringBuffer locationStr=new StringBuffer();
            for(Location location : user.getLines()){
                locationStr.append(",").append(location.getLocationId());
            }
            String str = locationStr.substring(1,locationStr.length());
            userForm.setSenderRegularLine(str);


        } else {
            userForm.setOtherLocation(user.getLocation());
            userForm.setOtherName(user.getUserName());
            userForm.setOtherRemark(user.getRemark());



            String qqs= "";
            for(UserContact userContact1:user.getContactList())
            {
                if(userContact1.getContactType()==UserContact.CONTACT_TYPE_MOBILE_PHONE){
                    userForm.setOtherName(userContact1.getContactName());
                    userForm.setOtherPhone(userContact1.getContactAccount());
                }else if(userContact1.getContactType() ==UserContact.CONTACT_TYPE_QQ){
                    qqs+=","+userContact1.getContactAccount();
                }
            }
            if(qqs.length()>0){
                qqs = qqs.substring(1,qqs.length());
            }
            userForm.setOtherQQ(qqs);

        }

        return userForm;
    }


    private UserDetail getUserDetail(UserForm userForm){

        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetail userDetail = new UserDetail();
        userDetail.setId(secUser.getUserId());
        userDetail.setEmail(userForm.getEmail());
        int userType = secUser.getUserType();
        //公司
        if (userType == User.USER_TYPE_COMPANY) {
            userDetail.setLocation(userForm.getCompanyLocation());
            userDetail.setUserName(userForm.getCompanyName());
            userDetail.setUserAddr(userForm.getCompanyAddr());

            List<UserContact> contacts = new ArrayList<UserContact>();
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getCompanyContactName());
            userContact.setContactAccount(userForm.getCompanyContactPhoneNo());
            contacts.add(userContact);
            //QQ
            if (StringUtils.isNotBlank(userForm.getCompanyQQ())) {
                String[] qqs = userForm.getCompanyQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }
            }


            userDetail.setContactList(contacts);

            userDetail.setShippingTypes(userForm.getCompanyShippingTypes());
            userDetail.getShippingTypes().removeAll(Collections.singleton(null));

            if (StringUtils.isNotBlank(userForm.getCompanyMajorLines())) {
                List<Location> majorLines = new ArrayList<Location>();
                String[] locations = userForm.getCompanyMajorLines().split(",");
                for (String locationId : locations) {
                    Location location1 = new Location(Integer.parseInt(locationId), null);
                    majorLines.add(location1);
                }
                userDetail.setLines(majorLines);
            }


        } else if (userType == User.USER_TYPE_SENDER) {
            userDetail.setLocation(userForm.getSenderLocation());
            userDetail.setUserName(userForm.getSenderName());
            List<UserContact> contacts = new ArrayList<UserContact>();
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getSenderName());
            userContact.setContactAccount(userForm.getSenderPhoneNo());
            contacts.add(userContact);
            //QQ
            if (StringUtils.isNotBlank(userForm.getSenderQQ())) {
                String[] qqs = userForm.getSenderQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }

            }

            userDetail.setContactList(contacts);
            List<Location> lines = new ArrayList<Location>();
            for(String lineStr :userForm.getSenderRegularLine().split(","))
            {
                if(StringUtils.isNotBlank(lineStr)){
                    Long locationId = Long.parseLong(lineStr);
                    Location location = new Location();
                    location.setLocationId(locationId);
                    lines.add(location);
                }


            }
            if(lines.size()>0){
                userDetail.setLines(lines);
            }



        } else {

            userDetail.setLocation(userForm.getOtherLocation());
            userDetail.setUserName(userForm.getOtherName());
            userDetail.setRemark(userForm.getOtherRemark());


            //��ϵ��
            List<UserContact> contacts = new ArrayList<UserContact>();
            //��ϵ�绰
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getOtherName());
            userContact.setContactAccount(userForm.getOtherPhone());
            contacts.add(userContact);

            //QQ
            if (StringUtils.isNotBlank(userForm.getOtherQQ())) {
                String[] qqs = userForm.getOtherQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }

            }
            userDetail.setContactList(contacts);


        }


        return  userDetail;
    }

}
